import { app } from 'electron';
import DefaultConfig from "@shared/constans/defaultConfig"
import Utils from "@main/common/utils"
import { IDefaultConfig } from "@shared/constans/types/configType"

const appPath = app.getPath('appData');
const path = require('path');
const fs = require('fs');

const currentAppData = path.join(appPath, DefaultConfig.name, DefaultConfig.version_name, "config.json");

const localConfig = {
    config_data: {} as {} | IDefaultConfig,

    getConfig(): IDefaultConfig | {} {
        if (fs.existsSync(currentAppData)) {
            this.config_data = Utils.ReadJsonFile(currentAppData);
          } else {
            console.error(`${currentAppData} 不存在`);
            return {};
          }
        return this.config_data
    },

    getConfigValue(key: string) {
        return this.config_data[key]
    },

    setConfig(key: string, value: any, type_key = undefined) {
        if (fs.existsSync(currentAppData)) {
            const current_data = Utils.ReadJsonFile(currentAppData)
            if (type_key) {
                current_data[type_key][key] = value
            } else {
                current_data[key] = value
            }
            Utils.WriteJsonFile(current_data, currentAppData)
        } else {
            this.initConfig()
            this.config_data = DefaultConfig
        }
    },

    saveSystemConfig(data) {
        if (fs.existsSync(currentAppData)) {
            this.config_data = Utils.ReadJsonFile(currentAppData) as IDefaultConfig
        } else {
            this.initConfig()
            this.config_data = DefaultConfig
        }
        if ("system_config" in this.config_data) {
            this.config_data.system_config = data
        }
        Utils.WriteJsonFile(this.config_data, currentAppData)
    },

    initConfig() {
        if (fs.existsSync(currentAppData)) {
            return
        } else {
            if (!fs.existsSync(path.dirname(currentAppData))){
                try {
                    fs.mkdirSync(path.dirname(currentAppData), { recursive: true });
                    console.log('目录创建成功:', currentAppData);
                  } catch (err) {
                    console.error('创建目录失败:', err);
                  }
            }
            Utils.WriteJsonFile(DefaultConfig, currentAppData)
        }
    }
}

export default localConfig;
